package com.cheung.shopkeeper.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {
	
	private static final String formateBeginDay = " 00:00:00";
	private static final String formateEndDay = " 23:59:59";
	private static final String formateStr10 = "yyyy-MM-dd";
	public static final String formateStr19 = "yyyy-MM-dd HH:mm:ss";
	private static long millSencondPerDay = 24 * 3600 * 1000;
	
	
	public static String formatDate(Date date, String fmt) {
		SimpleDateFormat sdf = new SimpleDateFormat(fmt);
		if (date == null) {
			return "";
		}
		return sdf.format(date);
	}
	
	public static Date parseDate(String str, String fmt) {
		SimpleDateFormat sdf = new SimpleDateFormat(fmt);
		if (str == null) {
			return null;
		}
		try {
			return sdf.parse(str);
		} catch (ParseException e) {
			return null;
		}
	}
	
	/**
	 * 将date偏移(增加或减少)N天
	 * @param date
	 * @param n 
	 * @return
	 */
	public static Date addDays(Date date,int n){
		long millSeconds = date.getTime();
		return new Date(millSeconds + n * millSencondPerDay);
	}
	
	/**
	 * 返回一天的起始时间点YYYY-MM-DD 00:00:00
	 * @param date
	 * @param n
	 * @return
	 */
	public static Date getStartDate(Date date) {
		String dayStr = formatDate(date, formateStr10);
		String begingDayStr = dayStr + formateBeginDay;
		return parseDate(begingDayStr, formateStr19);

	}
	
	/**
	 * 返回偏移n天后的起始时间点YYYY-MM-DD 00:00:00
	 * @param date
	 * @param n
	 * @return
	 */
	public static Date getStartDate(Date date,int n) {
		Date newDay = addDays(date, n);
		String dayStr = formatDate(newDay, formateStr10);
		String begingDayStr = dayStr + formateBeginDay;
		return parseDate(begingDayStr, formateStr19);

	}
	
	
	/**
	 * 返回一天的结束时间点YYYY-MM-DD 23:59:59
	 * @param date
	 * @return
	 */
	public static Date getEndDate(Date date) {
		String dayStr = formatDate(date, formateStr10);
		String endDayStr = dayStr + formateEndDay;
		return parseDate(endDayStr, formateStr19);
	}
	
	/**
	 * 返回偏移n天后的结束时间点YYYY-MM-DD 23:59:59
	 * @param date
	 * @param n
	 * @return
	 */
	
	public static Date addSecond(int n){
		Calendar cale = Calendar.getInstance();
		cale.add(Calendar.SECOND, n);
		return cale.getTime();
	}
	
	public static Date getEndDate(Date date,int n) {
		Date newDay = addDays(date, n);
		String dayStr = formatDate(newDay, formateStr10);
		String endDayStr = dayStr + formateEndDay;
		return parseDate(endDayStr, formateStr19);
	}
	
}
